
import gzip
import numpy as np
import re 

def GetTECFromInx(file_path):
    """
    Extract TEC (Total Electron Content) data from an index file.
    
    This function reads a file containing TEC maps and extracts the data
    organized by time periods (hours) and geographic coordinates (lines).
    
    Parameters:
    file_path (str): Path to the input file containing TEC data
    
    Returns:
    numpy.ndarray: 3D array with TEC data organized as [hour][line][values]
    """
    tecdata = list()
    # Initialize a list for each hour (0-23) to store TEC data for that hour
    tecdataline = [[] for i in range(24)]
    
    # Read the file content as binary and convert to numpy array
    with open(file_path, "rb") as f:  
        file_content = f.readlines()
        file_content = np.array(file_content)
    
    # Process each line in the file to find TEC map sections
    for idx in range(len(file_content)):
        # Look for lines indicating the start of a TEC map
        name = re.findall("START OF TEC MAP", str(file_content[idx]))
        if name != []:  # If we found a "START OF TEC MAP" marker
            # Extract the time information from the line
            time = re.findall("\\d+", str(file_content[idx]))
            # Skip if the time is outside the expected range (0-23 hours)
            if int(time[0]) - 1 >= 24:
                continue
            # Extract 71 lines of TEC data for this time period
            for line in range(71):
                # Extract numerical data from specific lines in the file
                tecdataline[int(time[0]) - 1].append(re.findall("\\d+", str(file_content[idx + 6 * line + 3:idx + 2 + 6 * (line + 1)])))
    
    # Convert the list to a numpy array for easier processing
    tecdataline = np.array(tecdataline) 
    return tecdataline